package B3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class StringExtractor {
    public static ArrayList<String> extractStringsFromFile(String filePath) {
        ArrayList<String> strings = new ArrayList<>();
        try {
            File file = new File(filePath);
            Scanner scanner = new Scanner(file, "UTF-8"); // 指定UTF-8编码读取

            boolean inString = false;
            StringBuilder currentString = new StringBuilder();

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                for (int i = 0; i < line.length(); i++) {
                    char currentChar = line.charAt(i);

                    if (currentChar == '"') {
                        if (inString) {
                            // 结束一个字符串
                            strings.add(currentString.toString());
                            currentString.setLength(0);
                            inString = false;
                        } else {
                            // 开始一个新字符串
                            inString = true;
                        }
                    } else if (inString) {
                        if (currentChar == '\\') {
                            // 处理转义字符，跳过下一个字符
                            i++;
                            currentString.append(line.charAt(i));
                        } else {
                            // 这里修正了错误的变量名，应该是currentString
                            currentString.append(currentChar);
                        }
                    }
                }
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return strings;
    }

    public static void main(String[] args) {
        // 手动设置文件路径
        String filePath = "D:\\Java\\javaProject\\softwareExperience_4\\src\\main\\java\\B3\\helloWorld.txt";

        ArrayList<String> extractedStrings = extractStringsFromFile(filePath);

        for (String str : extractedStrings) {
            System.out.println(str);
        }
    }
}